
package org.elanfox.intellicommunity.common.httputil;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.elanfox.intellicommunity.common.utils.StringUtilsExt;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @author guomw
 * @date 2019-10-19
 */
public class HttpClientUtil {
    private static final Log log = LogFactory.getLog(HttpClientUtil.class);

    private static CloseableHttpClient createHttpClient() {
        return HttpClientBuilder.create()
                .setDefaultRequestConfig(RequestConfig.custom()
                        .setConnectionRequestTimeout(30000)
                        .setConnectTimeout(30000)
                        .setSocketTimeout(30000).build()).build();
    }

    public static HttpResult post(String url, Map<String, String> requestMap) {
        return post(url, requestMap, null);
    }

    public static HttpResult post(String url, Map<String, String> requestMap, Map<String, String> header) {
        try (CloseableHttpClient httpClient = createHttpClient()) {

            List<NameValuePair> nameValuePairs = new ArrayList<>();
            HttpPost httpPost = new HttpPost(url);
            if (header != null) {
                header.forEach((key, value) -> {
                    httpPost.addHeader(key, value);
                });
            }
            requestMap.forEach((key, value) -> {
                if (value != null) {
                    nameValuePairs.add(new BasicNameValuePair(key, value));
                }
            });

            HttpEntity httpEntity = new UrlEncodedFormEntity(nameValuePairs, StringUtilsExt.ENCODING_UTF8);
            httpPost.setEntity(httpEntity);
            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                return new HttpResult(response.getStatusLine().getStatusCode(), EntityUtils.toString(response.getEntity()));
            }

        } catch (IOException e) {
            return new HttpResult(HttpStatus.SC_INTERNAL_SERVER_ERROR, e.getMessage());
        }
    }

    public static HttpResult post(String url, String requestData) {
        return post(url, requestData, null);
    }

    public static HttpResult post(String url, String requestData, Map<String, String> header) {
        try (CloseableHttpClient httpClient = createHttpClient()) {
            StringEntity stringEntity = new StringEntity(requestData, "utf-8");
            HttpPost httpPost = new HttpPost(url);
            if (header != null) {
                header.forEach((key, value) -> {
                    httpPost.addHeader(key, value);
                });
            }
            httpPost.setEntity(stringEntity);
            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                return new HttpResult(response.getStatusLine().getStatusCode(), EntityUtils.toString(response.getEntity()));
            }
        } catch (IOException e) {
            return new HttpResult(HttpStatus.SC_INTERNAL_SERVER_ERROR, e.getMessage());
        }

    }

    /**
     * 执行一个get请求
     *
     * @param url        请求地址
     * @param requestMap 请求参数
     * @return
     */
    public static HttpResult get(String url, Map requestMap) {
        try (CloseableHttpClient httpClient = createHttpClient()) {
            StringBuilder finalUrl = new StringBuilder(url);
            Iterator iterator = requestMap.entrySet().iterator();
            int index = 0;
            while (iterator.hasNext()) {
                Map.Entry entry = (Map.Entry) iterator.next();
                if (entry.getValue() != null) {
                    if (index == 0) {
                        finalUrl.append("?").append(entry.getKey()).append("=").append(entry.getValue());
                    } else {
                        finalUrl.append("&")
                                .append(entry.getKey()).append("=")
                                .append(URLEncoder
                                        .encode(String.valueOf(entry.getValue()), StringUtilsExt.ENCODING_UTF8));
                    }
                }
                index++;
            }
            HttpGet httpGet = new HttpGet(finalUrl.toString());
            try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
                return new HttpResult(response.getStatusLine().getStatusCode(), EntityUtils.toString(response.getEntity()));
            }
        } catch (IOException e) {
            return new HttpResult(HttpStatus.SC_INTERNAL_SERVER_ERROR, e.getMessage());
        }
    }
}
